#include "bsp_rcc.h"
#include "bsp_tim.h"
#include "bsp_uart.h"
#include "delay.h"
#include "do_mqtt.h"
#include "w55mh32_wztoe.h"
#include "wiz_interface.h"
#include "wizchip_conf.h"
#include <stdio.h>

#include "IR_Control.h"
#include "IR_Receive.h"
#include "RTC.h"
#include "ir_ac_control.h"

#define SOCKET_ID 0
#define ETHERNET_BUF_MAX_SIZE (1024 * 2)

// #define _IR_TEST_

/* network information */
wiz_NetInfo g_default_net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x12, 0x22, 0x05},
    .ip = {192, 168, 2, 40},
    .gw = {192, 168, 2, 1},
    .sn = {255, 255, 255, 0},
    .dns = {8, 8, 8, 8},
    .dhcp = NETINFO_DHCP};

unsigned char g_ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0};
unsigned char g_mqtt_send_ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0};
unsigned char g_mqtt_recv_ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {0};

// Structure defined by the IRext third-party library, used to store air conditioner status
t_remote_ac_status g_ac_status;
// g_brand
unsigned char g_brand = 0;
// model
unsigned char g_type = 0;
// g_operation
unsigned char g_operation = 0;

int main(void)
{
    /* clock initialization:
    Enable external high-speed crystal oscillator
    multiply the main frequency to 216MHz
    and set HCLK, PCLK1, and PCLK2 to 216MHz as well
    */
    rcc_clk_config();

    delay_init();

    console_usart_init(115200);

    tim3_init();

    printf("Infrared Remote Control Gateway\r\n");

    /* wiztoe init */
    wiz_toe_init();

    wiz_phy_link_check();

    network_init(g_ethernet_buf, &g_default_net_info);

    // ir init
    ir_config();
    ir_receive_init();

    // rtc init
    RTC_Init();

    mqtt_init(SOCKET_ID, g_mqtt_send_ethernet_buf, g_mqtt_recv_ethernet_buf);

    while (1)
    {
        do_mqtt();

        // Check whether the transmission command has been received
        if (ir_is_send())
        {
            // infrared control
            ir_control(g_brand, g_type, g_operation, &g_ac_status);

            reset_ir_send();

            ir_clear_data();
        }

        // Check if there is infrared data
        if (ir_is_ready())
        {
            printf("start IR learn\r\n");
            ir_learn();
        }
    }
}
